package com.ruoyi.common.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;

/** Redis缓存配置
 * @author LiuXiaoYu
 */
@Slf4j
public class MyRedisCacheManager extends RedisCacheManager {


    public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /**
     * 设置redis缓存时间
     * @param name 缓存名字
     * @param cacheConfig 缓存配置
     * @return RedisCache
     */
    @Override
    public RedisCache createRedisCache(String name,RedisCacheConfiguration cacheConfig) {
        if (!StringUtils.isEmpty(name) && name.contains("#")) {
            String[] numStr = name.split("#");
            if (StringUtils.isNumeric(numStr[1])) {
                //默认单位为秒，可根据需求拓展
                return super.createRedisCache(numStr[0], cacheConfig.entryTtl(Duration.ofSeconds(Integer.parseInt(numStr[1]))));
            }
        }
        //不包含则走默认时间 application.properties中配置的时间
        return super.createRedisCache(name, cacheConfig);
    }
}
